@extends('admin::public.base')
<style>
#user_list{
    display:none;
}
.layui-layer-content{
    position: relative;
}
body{
    overflow-y: scroll
}
.layui-table-cell .layui-form-checkbox[lay-skin=primary], .layui-table-cell .layui-form-radio[lay-skin=primary]{
    top:6px!important;
}
.user_btn{
    text-align: center;
    position: absolute;
    width: 100%;
    bottom: 10px;
}
.user_box{
    display:none;
}
.user_box .box{
    margin-right: 10px;
    display: inline-block;
    position: relative;
    background: #108cee;
    padding: 0px 10px;
    font-size: 12px;
    border-radius: 5px;
}
.user_box .box span{
    color:#ffffff;
}
.user_box .box em{
    position: absolute;
    right: -5px;
    font-size: 14px;
    display: inline-block;
    background: red;
    color: #fff;
    top: -5px;
    height: 15px;
    width: 15px;
    text-align: center;
    line-height: 15px;
    border-radius: 50%;
    cursor: pointer;
}
.send_time{
    display:none;
}
</style>
@section('content')
    <div class="layui-card">
        <div class="layui-card-header layuiadmin-card-header-auto">
            <header class="title">添加消息<div class="word-aux">------<span style="color:#108cee">消息详情</span>和<span style="color:#108cee">消息链接</span>只填一处便可，默认展示<span style="color:#108cee">消息详情</span></div></header>
        </div>
        <div class="layui-card-body">
            <div action="" class="layui-form">
                <div class="layui-form-item">
                    <label for="" class="layui-form-label layui-required">消息类型</label>
                    <div class="layui-input-block">
                        <select name="type" id="">
                            @foreach ($types as $key=>$item)
                                <option value="{{$key}}">{{$item}}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label layui-required">消息标题</label>
                    <div class="layui-input-block">
                        <input class="layui-input" type="text" autocomplete="off" name="title" id="title" placeholder="请输入消息标题">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label layui-required">消息内容</label>
                    <div class="layui-input-block">
                        <textarea name="content" id="content" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label">消息图片</label>
                    <div class="layui-input-block">
                        <div class="app-image-box">
                        </div>
                        <div class="app-btn-file"><input type="file" name="logo" accept="image/*" class="app-image"  onchange="imageCallBack(this)"/>
                        <div class="app-btn-name"><p class="fa fa-folder-open-o"></p><h1>上传图片</h1></div></div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label layui-required">发送群体</label>
                    <div class="layui-input-block">
                        <input type="radio" name="user_type" checked value="1" title="全部用户" lay-filter="user_type">
                        <input type="radio" name="user_type" value="2" title="部分用户" lay-filter="user_type">
                    </div>
                </div>
                <div class="layui-form-item user_box">
                    <div class="layui-input-block" style="padding: 10px;border:1px solid #e6e6e6;">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label layui-required">发送方式</label>
                    <div class="layui-input-block">
                        <input type="radio" name="send_type" checked value="1" title="即时" lay-filter="send_type">
                        <input type="radio" name="send_type" value="2" title="定时" lay-filter="send_type">
                    </div>
                </div>
                <div class="layui-form-item send_time">
                    <div class="layui-input-block " >
                        <div class="layui-input-inline" style="width:auto;padding: 5px 0px;">
                            选择时间：
                        </div>
                        <div class="layui-input-inline">
                            <input type="text" name="send_time" class="layui-input" id="send_time">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label">消息链接</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" autocomplete="off" name="url" id="url" placeholder="请输入完整的url链接">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="" class="layui-form-label">消息详情</label>
                    <div class="layui-input-block">
                        <textarea name="detail" id="detail" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">确 认</button>
                        <a href="javascript:history.back(-1);" class="layui-btn layui-btn-primary" >返 回</a>
                    </div>
                </div>
                <div id="user_list">
                    <div class="layui-header">
                        <div class="layui-card-header layuiadmin-card-header-auto">
                            <div class="layui-input-inline">
                                <input type="text" name="filter" value="" id="filter" autocomplete="off" placeholder="请输入用户昵称|手机号" class="layui-input layui-search">
                            </div>
                            <div class="layui-input-inline">
                                <button type="submit" class="layui-btn layui-btn-search" onclick="reload();">查询</button>
                            </div>
                        </div>
                    </div>
                    <table id="dataTable" class="layui-hide" lay-filter="dataTable"></table>
                    <div class="layui-form-item user_btn">
                        <button type="submit" class="layui-btn" onclick="user_confirm();">确 认</button>
                        <a href="javascript:layer.closeAll();" class="layui-btn layui-btn-primary" >取 消</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
@section('script')
<script src="/static/common/plugins/kindeditor/kindeditor-all.js"></script>
<script src="/static/common/plugins/kindeditor/lang/zh-CN.js"></script>
    <script>
        layui.use(['layer','form','table','laydate'],function () {
            var form = layui.form;
            var layer = layui.layer;
            var table = layui.table;
            var laydate = layui.laydate;
            var user = [];
            var image = "";
            laydate.render({
                elem: '#send_time',
                min: 0,
                type:'datetime',
                theme: '#108cee',
                trigger: 'click'
            });
            //监听发送群体单选框
            form.on('radio(user_type)', function(data){
                if(data.value==2){
                    //部分用户
                    layer.open({
                        type: 1,
                        content: $('#user_list'),
                        title: '选择用户',
                        skin:'layui-skin',
                        offset: '100px',
                        area: ['650px', '530px'],
                        shade: 0.8,
                    });
                    $('.user_box').show();
                }else{
                    $('.user_box').hide();
                }
            });
            //监听发送方式单选框
            form.on('radio(send_type)',function(data){
                if(data.value==2){
                    //定时
                    $('.send_time').show();
                }else{
                    //即时
                    $('.send_time').hide();
                }
            })
            //富文本编辑器
            window.editor = KindEditor.create('#detail', {
                height: '300px',
                width:'100%',
                themeType: 'default',
                allowPreviewEmoticons: false,
                allowImageUpload: true,
                allowFileManager: true,
                uploadJson: "{{ route('admin.editorUpload') }}",
                afterBlur: function(){ this.sync(); },
                afterUpload: function (url) {
                    this.sync();
                },
                items: [
                    'undo', 'redo','|','justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent','|',
                    'fontname', 'fontsize','forecolor', 'hilitecolor', 'bold',
                    'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat','|','image', 'multiimage',
                    'emoticons','link', 'unlink'
                ]
            });
            //用户表格初始化
            var dataTable = table.render({
                elem: '#dataTable'
                ,url: "{{ route('admin.userList') }}" //数据接口
                ,skin:'line'
                ,text: { //自定义文本，此处用法--》当返回数据为空时的异常提示
                    none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
                }
                ,cols: [[ //表头
                    {checkbox: true}
                    ,{field: 'nickname',width:'150',align:'center',  title: '用户昵称'}
                    ,{field: 'sex_msg',width:'100',align:'center',  title: '性别'}
                    ,{field: 'phone', width:'150',align:'center', title: '手机号'}
                    ,{field: 'create_time',width:'200',align:'center',  title: '注册时间'}
                ]]
                ,done: function(res, page, count){
                    var ids = user.map(function (item) {
                    　　　　 return item['id'];
                    });
                    //可以自行添加判断的条件是否选中
                    //这句才是真正选中，通过设置关键字LAY_CHECKED为true选中，这里只对第一行选中
                    for(var i=0;i<res.data.length;i++){
                        if($.inArray(res.data[i].id,ids)>=0){
                            res.data[i]["LAY_CHECKED"]='true';
                            //下面三句是通过更改css来实现选中的效果
                            var index= res.data[i]['LAY_TABLE_INDEX'];
                            $('tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                            $('tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                        }
                    }
                }
            });
            //确认用户
            window.user_confirm = function(){
                var checkStatus = table.checkStatus('dataTable').data;
                var ids = user.map(function (item) {
                　　　　 return item['id'];
                });
                var html = '';
                for(var i=0;i<checkStatus.length;i++){
                    if($.inArray(checkStatus[i].id,ids)<0){
                        user.push({id:checkStatus[i].id,'nickname':checkStatus[i].nickname});
                        html += '<div class="box"><span data-id="'+checkStatus[i].id+'">'+checkStatus[i].nickname+'</span><em onclick="delId(this)" title="删除">×</em></div>';
                    }
                }
                $('.user_box').find('.layui-input-block').append(html);
                layer.closeAll();
            }
            //删除用户
            window.delId = function(obj){
                var id = $(obj).parent().find('span').attr('data-id');
                for(var i=0;i<user.length;i++){
                    if(id==user[i].id){
                        user.splice(i, 1);
                    }
                }
                $(obj).parent().remove();
                reload();
            }
            //监听复选框
            table.on('checkbox(dataTable)', function(obj){
                if(obj.checked){
                    if(obj.type=="all"){
                        $('.layui-table').find('tbody tr').attr({"style":"background:#f5fbff"});
                    }else{
                        var index = obj.data.LAY_TABLE_INDEX;
                        $('.layui-table').find('tbody tr').eq(index).attr({"style":"background:#f5fbff"});
                    }
                }else{
                    if(obj.type=="all"){
                        $('.layui-table').find('tbody tr').attr({"style":"background:#ffffff"});
                    }else{
                        var index = obj.data.LAY_TABLE_INDEX;
                        $('.layui-table').find('tbody tr').eq(index).attr({"style":"background:#ffffff"});
                    }
                }
            });
            //重载表格
            window.reload = function(){
                dataTable.reload()
            }
            //单图片上传
            window.imageCallBack = function(obj){
                var file = obj.files[0];
                var path = window.uploadBack(file);
                var html = '<div class="box">';
                html += '<input type="hidden" value="'+path+'"/>'
                html += '<img src="'+path+'" title="'+file.name+'" />';
                html += '<em onclick="delImage(this)" title="删除">×</em>';
                html += '</div>';
                $(obj).parent().prev('.app-image-box').html(html);
                $(obj).parent().prev('.app-image-box').viewer('update');
                image = file;
            }
            //删除单图
            window.delImage = function (obj) {
                $(obj).parent().parent().next('.app-btn-file').find('input').val("");
                $(obj).parent().remove();
                image = "";
            }
            //表单提交
            form.on('submit(submit)', function (data) {
                //验证表单
                var formData = new FormData();
                if (!data.field.title) {
                    layer.msg('请输入消息标题');
                    return false;
                }
                if (!data.field.content) {
                    layer.msg('请输入消息内容');
                    return false;
                }
                if(!data.field.url&&!data.field.detail){
                    layer.msg('请填写消息详情或链接');
                    return false;
                }
                if(image){
                    formData.append('logo',image);
                }
                formData.append('title',data.field.title);
                formData.append('content',data.field.content);
                formData.append('url',data.field.url);
                formData.append('detail',data.field.detail);
                formData.append('user_type',data.field.user_type);
                if(data.field.send_time){
                    formData.append('send_time',data.field.send_time);
                }else{
                    formData.append('send_time',"");
                }
                formData.append('type',data.field.type);
                for(var i=0;i<user.length;i++){
                    formData.append('user[]',user[i].id);
                }
                //ajax提交
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "{{route('admin.message.store')}}",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        if (data.code == 1) {
                            layer.msg(data.msg, {
                                time: 2000
                            }, function () {
                                location.href = "{{route('admin.message')}}";
                            })
                        } else {
                            layer.msg(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg("服务器开小差啦");
                    }
                });
            })
        });
    </script>
@endsection

